package com.nx.platform.es.biz.esspider.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreMaps;
import com.nx.platform.es.common.utils.MoreSplitters;
import org.apache.logging.log4j.util.Strings;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * Created by JY on 2018/9/9.
 *
 * @Description: 提取json数据
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleJsonExtractHandler extends AbstractSimpleHandler {

    private String field;
    private String[] destFields;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        field = MoreMaps.getString(settings, "field");
        destFields = MoreMaps.getStringArray(settings, "destFields", MoreSplitters.COMMA);
        Preconditions.checkArgument(Strings.isNotBlank(field), "field null or empty");
        Preconditions.checkArgument(Objects.nonNull(destFields) && destFields.length > 0,
                "destFields null or empty");
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {

        items.values().forEach((Item item) -> {
            Map<String, Object> doc = item.getDoc();
            Object json = doc.get(field);
            JSONObject jsonObject;
            if (Objects.nonNull(json) && !(jsonObject = parseJson(json)).isEmpty()) {
                doc.remove(field);
                Stream<String> fieldNames = Stream.of(destFields).distinct();
                fieldNames.forEach(key -> {
                    if (key.contains(MoreSplitters.COLON.pattern())) {
                        String[] keyPair = MoreSplitters.COLON.split(key);
                        doc.put(keyPair[1].trim(), jsonObject.get(keyPair[0].trim()));
                    } else {
                        doc.put(key, jsonObject.get(key));
                    }
                });
            }
        });
    }

    private static JSONObject parseJson(Object content) {
        try {
            JSONObject json = JSONObject.parseObject(content.toString());
            return json == null ? new JSONObject() : json;
        } catch (Exception e) {
            return new JSONObject();
        }
    }
}
